<template>
  <div>
    <div class="search-title">查询条件</div>
    <div class="search-box">
      <a-form-model :model="searchForm" layout="inline" ref="searchForm" class="searchForm">
        <a-form-model-item label="题库名称" prop="title">
          <a-input v-model="searchForm.title" placeholder="请输入题库名称" />
        </a-form-model-item>
        <a-form-model-item class="searchButton">
          <a-button type="primary" v-if="QX.read" @click="getSearch">查询</a-button>
          <a-button type="default" v-if="QX.read" @click="restSearch('searchForm')">重置</a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="table-operation">
      <a-button type="primary" @click="addBank" icon="plus" v-if="QX.add">新增</a-button>
      <el-tooltip content="点击此按钮将初始化npc课程数据" placement="top">
        <a-button type="primary" @click="updateUserCourse"  icon="reload">初始化</a-button>

      </el-tooltip>
    </div>
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="false"
      :loading="loading"
      rowKey="questionBankId"
      :scroll="{ y: this.$getViewportSize().height - 300 }"
    >
      <span slot="action" slot-scope="text, record">
        <a @click="editAuth(record)" v-if="QX.edit"><a-icon class="iconBtn" type="edit" />编辑</a>
        <a-divider v-if="QX.edit && QX.delete" type="vertical" />
        <a-popconfirm
          title="确认是否删除？"
          ok-text="是"
          cancel-text="否"
          @confirm="removeBank(record)"
        >
          <a v-if="QX.delete"><a-icon class="iconBtn" type="delete" />删除</a>
        </a-popconfirm>
      </span>
    </a-table>

    <template slot="action" slot-scope="text, record, index">
      <a @click="removeQuestion(index)">删除</a>
    </template>

    <a-pagination
      show-size-changer
      :total="totalPage"
      :current="pageIndex"
      :pageSize="pageSize"
      @showSizeChange="onShowSizeChange"
      @change="onChangePage"
      style="float: right; margin-top: 15px"
    />
    <a-drawer
      :closable="true"
      :title="title"
      width="auto"
      :visible="visible"
      @close="visible = !visible"
    >
      <a-spin class="submitLoading" :spinning="submitLoading">
        <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules" ref="form" class="lay-drawer-form">
          <a-row>
            <a-col :span="12">
              <a-form-model-item label="题库名称" prop="title">
                <a-input v-model="form.title" :maxLength="25" placeholder="请输入题库名称" style="width: 380px" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="关联岗位" prop="positionId">
                <a-select
                  v-model="form.positionId"
                  style="width: 380px"
                  placeholder="请选择岗位"
                  @change="handlePositionChange"
                >
                  <a-select-option v-for="(label, value) in positionDict" :key="value" :value="value">
                    {{ label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="参与PK" prop="participateInPk">
                <a-switch v-model="form.participateInPk" :checkedValue="1" :unCheckedValue="0" />
              </a-form-model-item>
            </a-col>
            <!-- 当不参与PK时显示的下拉框 -->
            <a-col :span="12" v-if="!form.participateInPk">
              <a-form-model-item label="关联课程" prop="courseId" :rules="!form.participateInPk ? [{ required: true, message: '请选择关联课程', trigger: 'change' }] : []">
                <a-select
                  v-model="form.courseId"
                  style="width: 380px"
                  placeholder="请选择课程"
                  show-search
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  :not-found-content="courseLoading ? '加载中...' : courseList.length === 0 ? '无匹配课程' : null"
                >
                  <a-select-option v-for="course in courseList" :key="course.id" :value="course.id">
                    {{ course.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <!-- 新增题目区域 -->
        <div class="question-batch">
          <div style="margin: 20px 0; display: flex; justify-content: space-between; align-items: center;">
            <a-button type="primary" @click="downloadTemplate">下载模板</a-button>
            <div class="import-add-buttons">
              <a-upload
                name="file"
                :showUploadList="false"
                :beforeUpload="beforeUpload"
                accept=".xlsx,.xls"
                :disabled="!importEnabled"
              >
                <a-button :disabled="!importEnabled"><a-icon type="upload" /> 导入题目</a-button>
              </a-upload>
              <a-button
                type="dashed"
                @click="addTopicVisible = true"
                :disabled="!addEnabled"
              >
                <a-icon type="plus" /> 添加题目
              </a-button>
            </div>
          </div>

          <!-- 题目列表容器添加样式 -->
          <div class="topic-list-container">
            <!-- 题目列表 -->
            <div class="topic-grid">
              <!-- 题目编号和内容 -->
              <div v-for="(topic, index) in topicList" :key="topic.topicId" class="topic-item">
                <!-- 题目编号和内容 -->
                <div class="topic-content">
                  <strong>{{ index + 1 }}. {{ topic.content }}</strong>
                </div>

                <!-- 选项列表 -->
                <div class="options" v-if="topic.topicType === 1">
                  <label v-for="option in getOptions(topic)" :key="option.key">
                    <input
                      type="radio"
                      :name="'topic' + topic.topicId"
                      :value="option.key"
                      :checked="topic.correctAnswer === option.key"
                    />
                    {{ option.key }}. {{ option.value }}
                  </label>
                </div>
                <!-- 判断题 -->
                <div v-if="topic.topicType === 2" class="options">
                  <label>
                    <input
                      type="radio"
                      :name="'topic' + topic.topicId"
                      value="正确"
                      :checked="topic.correctAnswer === '正确'"
                    />
                    正确
                  </label>
                  <label>
                    <input
                      type="radio"
                      :name="'topic' + topic.topicId"
                      value="错误"
                      :checked="topic.correctAnswer === '错误'"
                    />
                    错误
                  </label>
                </div>
                <!-- 删除按钮 -->
                <div class="topic-delete">
                  <a @click="removeQuestion(topic.topicId)">
                    <a-icon type="delete" /> 删除
                  </a>
                </div>
              </div>
            </div>

            <!-- 分页组件 -->
            <div class="pagination-wrapper">
              <a-pagination
                v-model="topicPageNum"
                :pageSize="topicPageSize"
                :total="totalTopicCount"
                @change="handleTopicPageChange"
                style="text-align: right;"
              />
            </div>
          </div>

        </div>
        <div
          :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '8px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }">
          <a-button
            type="default"
            @click="visible = !visible"
          >
            取消
          </a-button>
          <a-button
            type="primary"
            @click="submitForm"
          >
            确认
          </a-button>
        </div>
      </a-spin>
    </a-drawer>
    <!-- 新增题目抽屉 -->
    <a-drawer
      title="新增题目"
      :visible="addTopicVisible"
      @close="addTopicVisible = false"
      width="500"
    >
      <a-form-model :model="addTopicForm" layout="vertical" :rules="rulesForAddTopic" ref="addTopicFormRef">
        <!-- 题目类型 -->
        <a-form-model-item label="题目类型" prop="topicType">
          <a-select v-model="addTopicForm.topicType" style="width: 100%">
            <a-select-option :value="1">选择题</a-select-option>
            <a-select-option :value="2">判断题</a-select-option>
          </a-select>
        </a-form-model-item>

        <!-- 题目内容 -->
        <a-form-model-item label="题目内容" prop="content">
          <a-input v-model="addTopicForm.content" placeholder="请输入题目内容" />
        </a-form-model-item>

        <!-- 选择题选项 -->
        <div v-if="addTopicForm.topicType === 1">
          <a-form-model-item label="选项A" prop="optionA">
            <a-input v-model="addTopicForm.optionA" placeholder="请输入选项A内容" />
          </a-form-model-item>
          <a-form-model-item label="选项B" prop="optionB">
            <a-input v-model="addTopicForm.optionB" placeholder="请输入选项B内容" />
          </a-form-model-item>
          <a-form-model-item label="选项C" prop="optionC">
            <a-input v-model="addTopicForm.optionC" placeholder="请输入选项C内容" />
          </a-form-model-item>
          <a-form-model-item label="选项D" prop="optionD">
            <a-input v-model="addTopicForm.optionD" placeholder="请输入选项D内容" />
          </a-form-model-item>
          <a-form-model-item label="正确答案" prop="correctAnswer">
            <a-select v-model="addTopicForm.correctAnswer" style="width: 100%">
              <a-select-option value="A">A</a-select-option>
              <a-select-option value="B">B</a-select-option>
              <a-select-option value="C">C</a-select-option>
              <a-select-option value="D">D</a-select-option>
            </a-select>
          </a-form-model-item>
        </div>

        <!-- 判断题选项 -->
        <div v-if="addTopicForm.topicType === 2">
          <a-form-model-item label="正确答案" prop="correctAnswer">
            <a-select v-model="addTopicForm.correctAnswer" style="width: 100%">
              <a-select-option value="正确">正确</a-select-option>
              <a-select-option value="错误">错误</a-select-option>
            </a-select>
          </a-form-model-item>

        </div>


        <div class="drawer-footer">
          <a-button @click="addTopicVisible = false">取消</a-button>
          <a-button type="primary" @click="saveNewTopic">保存</a-button>
        </div>
      </a-form-model>
    </a-drawer>
  </div>
</template>

<script>
import { req, fileDownload } from '../../../api/axiosFun';
import preventBack from 'vue-prevent-browser-back';

export default {
  name: 'Bank',
  mixins: [preventBack],
  data() {
    return {
      QX: {},
      topicQX: {},
      topicList: [],
      totalTopicCount: 0, // 题目总数
      topicPageNum: 1, // 当前页码
      topicPageSize: 10, // 每页数量
      addTopicVisible: false,
      addTopicForm: {
        content: '', // 题目内容
        topicType: 1, // 题目类型：1=选择题，2=判断题
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: '',
        correctAnswer: '',
      },
      disabled: false,
      checkedKeys: [],
      selectAuth: [],
      treeData: [],
      positionDict: {},
      courseList: [], // 课程列表数据
      courseLoading: false, // 课程数据加载状态
      title: '',
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      tableHeight: 0,
      expanded: false, // 筛选条件是否展开
      form: {
        questionBankId: 0,
        bankCode: '',
        title: '',
        positionId: '',
        participateInPk: true,
        courseId: '', // 关联课程ID
      },
      isEdit: false, // 是否是编辑状态
      isAdd: false, // 是否是新增状态
      importEnabled: false, // 导入题目按钮是否可用 - 默认为不可用
      addEnabled: false, // 添加题目按钮是否可用 - 默认为不可用
      rules: {
        positionId: [
          { required: true, message: '请选择岗位', trigger: 'change' },
        ],
        title: [
          { required: true, message: '请输入题库名称', trigger: 'blur' },
        ],
      },
      rulesForAddTopic: {
        content: [
          { required: true, message: '请输入题目内容', trigger: ['blur', 'change'] },
        ],
        topicType: [
          { required: true, message: '请选择题目类型', trigger: 'change' },
        ],
        optionA: [
          {
            required: (rule, value) => this.addTopicForm.topicType === 1,
            message: '选择题必须输入选项A',
            trigger: ['blur', 'change'],
          },
        ],
        optionB: [
          {
            required: (rule, value) => this.addTopicForm.topicType === 1,
            message: '选择题必须输入选项B',
            trigger: ['blur', 'change'],
          },
        ],
        optionC: [
          {
            required: (rule, value) => this.addTopicForm.topicType === 1,
            message: '选择题必须输入选项C',
            trigger: ['blur', 'change'],
          },
        ],
        optionD: [
          {
            required: (rule, value) => this.addTopicForm.topicType === 1,
            message: '选择题必须输入选项D',
            trigger: ['blur', 'change'],
          },
        ],
        correctAnswer: [
          { required: true, message: '请选择正确答案', trigger: 'change' },
        ],
      },
      searchForm: {
        title: '',
      },
      visible: false,
      dataList: [],
      columns,
      loading: false,
      submitLoading: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      ops: {
        vuescroll: {},
        scrollPanel: {},
        rail: {
          keepShow: true,
        },
        bar: {
          hoverStyle: true,
          onlyShowBarOnScroll: false, // 是否只有滚动的时候才显示滚动条
          background: '#F5F5F5', // 滚动条颜色
          opacity: 1, // 滚动条透明度
          'overflow-x': 'hidden',
        },
      },
    };
  },
  watch: {
    'addTopicForm.topicType': function (newVal) {
      // 当题目类型变化时，触发相关字段的验证
      this.$nextTick(() => {
        if (this.$refs.addTopicFormRef) {
          // 验证选项字段
          if (newVal === 1) {
            this.$refs.addTopicFormRef.validateFields(['optionA', 'optionB', 'optionC', 'optionD']);
          } else {
            // 清除非必填字段的验证状态
            this.$refs.addTopicFormRef.clearValidate(['optionA', 'optionB', 'optionC', 'optionD']);
          }
        }
      });
    },
    // 监听参与PK状态变化，加载课程数据
    'form.participateInPk': function (newVal) {
      // 当不参与PK时，加载课程列表
      if (!newVal) {
        this.loadCourseList('');
      } else {
        // 参与PK时清空课程选择
        this.form.courseId = '';
      }
    },
    visible(newVal, oldVal) {
      if (!newVal) {
        this.restForm('form');
        this.form.questionBankId = 0;
        this.checkedKeys = [];
        this.selectAuth = [];
        this.treeData = [];
        // 重置状态标志
        this.isEdit = false;
        this.isAdd = false;
      } else {
        // 当抽屉打开时强制更新按钮状态
        this.$nextTick(() => {
          this.$forceUpdate();
        });
        // 如果是编辑状态且不参与PK，加载课程数据
        if (this.isEdit && !this.form.participateInPk) {
          this.loadCourseList('');
        }
      }
    },
  },
  mounted() {
    this.actionTitle = '操作';
    this.getDict('position').then((res) => {
      const dictMap = {};
      res.data.forEach((item) => {
        dictMap[item.dicValue.toString()] = item.dicDisplayName;
      });
      this.positionDict = dictMap;
    });
    this.getBankList();
  },
  methods: {
    // 新增：处理岗位变化事件
    handlePositionChange() {
      // 当不参与PK且岗位发生变化时
      if (!this.form.participateInPk) {
        // 清空关联课程
        this.form.courseId = '';
        // 重新查询课程列表
        this.loadCourseList('');
      }
    },

    getDict(key) {
      return req('post', '/dict/getDictItemByNo', { dicNo: key });
    },
    /* 新增题库 */
    addBank() {
      this.visible = true;
      this.disabled = false;
      this.title = '新增题库';
      // 获取功能权限树
      req('get', '/bank/getTree', {}).then((res) => {
        this.treeData = res.data;
      });
      // 初始化题目列表为空
      this.topicList = [];
      this.totalTopicCount = 0;
      this.topicPageNum = 1;
      this.isEdit = false; // 不是编辑状态
      this.isAdd = true; // 设置为新增状态
      // 在新增状态下禁用导入和添加功能
      this.importEnabled = false;
      this.addEnabled = false;
      // 重置课程相关字段
      this.form.courseId = '';
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    // 查询
    getSearch() {
      this.pageIndex = 1;
      this.getBankList();
    },
    /* 重置查询 */
    restSearch(form) {
      this.restForm(form);
      this.pageIndex = 1;
      this.getBankList();
    },
    /* 删除题库 */
    removeBank(record) {
      this.loading = true;
      req('post', '/bank/removeBQuestionBank', {
        questionBankId: record.questionBankId,
      }).then((res) => {
        this.loading = false;
        if (res.result === 'success') {
          this.$message.success(res.message);
          this.getBankList();
        }
      });
    },

    downloadTemplate() {
      fileDownload('get', '/topic/downloadTemplate', null).then((res) => {
        const blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });

        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '题库模板.xlsx';
        link.click();
        window.URL.revokeObjectURL(link.href);
      }).catch(() => {
        this.$message.error('下载失败');
      });
    },

    beforeUpload(file) {
      this.loading = true;

      const formData = new FormData();
      formData.append('file', file);
      formData.append('questionBankId', this.form.questionBankId);
      formData.append('courseId', this.form.courseId);

      req('post', '/topic/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
        .then((res) => {
          this.loading = false;
          if (res.result === 'success') {
            this.$nextTick(() => {
              this.getTopicList(this.form.questionBankId, this.topicPageNum, this.topicPageSize)
                .then(() => {
                  this.$message.success('导入成功');
                })
                .catch(() => {
                  this.$message.error('刷新题目列表失败');
                });
            });
          } else {
            this.$message.error(res.message || '导入失败');
          }
        })
        .catch((error) => {
          this.loading = false;
          this.$message.error('导入失败，请重试');
          console.error('导入题目出错:', error);
        });

      return false;
    },

    // 获取题库下的题目列表
    getTopicList(questionBankId, pageNum = 1, pageSize = 10) {
      return new Promise((resolve, reject) => {
        req('post', '/topic/list', {
          questionBankId,
          page: pageNum,
          rows: pageSize,
        }).then((res) => {
          if (res.result === 'success') {
            this.topicQX = res.QX;
            if (!this.topicQX.edit && !this.topicQX.delete) {
              this.hideAction();
            } else {
              this.topicList = res.data.map((item, index) => ({
                index: (pageNum - 1) * pageSize + index + 1,
                content: item.content,
                optionA: item.optionA,
                optionB: item.optionB,
                optionC: item.optionC,
                optionD: item.optionD,
                topicId: item.topicId,
                correctAnswer: item.correctAnswer,
                topicType: item.topicType,
              }));
            }
            this.totalTopicCount = res.page.totalResult;
            resolve(res);
          } else {
            this.$message.error(res.message || '获取题目列表失败');
            reject(res);
          }
        }).catch((error) => {
          this.$message.error('获取题目列表失败');
          reject(error);
        });
      });
    },

    handleTopicPageChange(page) {
      this.topicPageNum = page;
      this.getTopicList(this.form.questionBankId, page, this.topicPageSize);
    },

    //名称下拉选择输入过滤
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },

    // 获取选择题的选项
    getOptions(topic) {
      if (topic.topicType === 1) {
        const options = [];
        if (topic.optionA) options.push({ key: 'A', value: topic.optionA });
        if (topic.optionB) options.push({ key: 'B', value: topic.optionB });
        if (topic.optionC) options.push({ key: 'C', value: topic.optionC });
        if (topic.optionD) options.push({ key: 'D', value: topic.optionD });
        return options;
      } else if (topic.topicType === 2) {
        return [
          { key: '正确', value: '正确' },
          { key: '错误', value: '错误' },
        ];
      }
      return [];
    },

    resetAddTopicForm() {
      this.addTopicForm = {
        content: '',
        topicType: 1,
        optionA: '',
        optionB: '',
        optionC: '',
        optionD: '',
        correctAnswer: '',
      };
    },

    saveNewTopic() {
      this.$refs.addTopicFormRef.validate((valid, fields) => {
        if (!valid) {
          console.log('表单验证失败:', fields);
          const firstErrorField = Object.keys(fields).find(key => fields[key]);
          if (firstErrorField && this.$refs.addTopicFormRef) {
            const formItem = this.$refs.addTopicFormRef.$children.find(
              child => child.prop === firstErrorField,
            );
            if (formItem && formItem.$el) {
              const input = formItem.$el.querySelector('input, select, textarea');
              if (input) input.focus();
            }
          }
          return;
        }

        const newTopic = { ...this.addTopicForm };
        req('post', '/topic/add', {
          questionBankId: this.form.questionBankId,
          courseId: this.form.courseId,
          optionA: newTopic.optionA,
          optionB: newTopic.optionB,
          optionC: newTopic.optionC,
          optionD: newTopic.optionD,
          correctAnswer: newTopic.correctAnswer,
          content: newTopic.content,
          topicType: newTopic.topicType,
        }).then((res) => {
          if (res.result === 'success') {
            this.$message.success('题目添加成功');
            this.addTopicVisible = false;
            this.getTopicList(this.form.questionBankId);
          } else {
            this.$message.error(res.message || '保存失败');
          }
          this.resetAddTopicForm();
        }).catch((err) => {
          this.$message.error('网络异常，请重试');
        });
      });
    },

    /* 删除题库下的题目 */
    removeQuestion(topicId) {
      this.$confirm({
        title: '确认删除该题目？',
        content: '删除后将无法恢复',
        okText: '是',
        cancelText: '否',
        onOk: () => {
          req('post', '/topic/removeBTopic', {
            topicId,
            questionBankId: this.form.questionBankId,
            courseId: this.form.courseId,
          }).then((res) => {
            if (res.result === 'success') {
              this.$message.success(res.message);
              this.getTopicList(this.form.questionBankId, this.topicPageNum, this.topicPageSize);
            } else {
              this.$message.error(res.message || '删除失败');
            }
          });
        },
      });
    },

    editAuth(record) {
      this.loading = true;
      req('post', '/bank/getBQuestionBank', {
        questionBankId: record.questionBankId,
      }).then((res) => {
        this.loading = false;
        if (res.result === 'success') {
          this.visible = true;
          this.disabled = true;
          this.title = '修改题库';
          this.isEdit = true;
          this.isAdd = false;
          this.importEnabled = true;
          this.addEnabled = true;

          const bank = res.data;
          this.$nextTick(() => {
            this.form.questionBankId = bank.questionBankId;
            this.form.title = bank.title;
            this.form.participateInPk = Boolean(bank.participateInPk);
            this.form.positionId = String(bank.positionId);
            // 设置课程ID
            this.form.courseId = bank.courseId || '';
            this.treeData = bank.treeData;
            this.checkedKeys = bank.auths;
            this.$forceUpdate();
            this.topicPageNum = 1;
            this.getTopicList(bank.questionBankId, this.topicPageNum, this.topicPageSize);
            // 如果不参与PK，加载课程列表
            if (!this.form.participateInPk) {
              this.loadCourseList('');
            }
          });
        }
      });
    },

    /* 加载课程列表 */
    loadCourseList(keyword = '') {
      if (this.courseLoading) return;
      if (!this.form.positionId) {
        this.courseList = [];
        this.$message.warning('请先选择岗位');
        return;
      }

      this.courseLoading = true;
      req('post', '/course/getBCourseByPosition', {
        positionId: this.form.positionId,
        keyword: keyword.trim()
      }).then((res) => {
        this.courseLoading = false;
        if (res.result === 'success') {
          this.courseList = res.data.map(item => ({
            id: item.courseId,
            name: item.courseTitle,
          }));
        } else {
          this.$message.error(res.message || '获取课程列表失败');
          this.courseList = [];
        }
      }).catch((error) => {
        this.courseLoading = false;
        this.$message.error('获取课程列表失败，请重试');
        console.error('加载课程列表出错:', error);
      });
    },

    /* 保存or修改题库信息 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.participateInPk = this.form.participateInPk ? 1 : 0;
          const url = this.form.questionBankId ? 'edit' : 'add';
          const selectAuth = this.selectAuth;
          this.form.selectAuth = JSON.stringify(selectAuth);
          this.submitLoading = true;
          req('post', `/bank/${url}`, this.form).then((res) => {
            if (res.result === 'success') {
              this.visible = false;
              this.getBankList();
              if (!this.form.questionBankId && res.data && res.data.questionBankId) {
                this.form.questionBankId = res.data.questionBankId;
                this.topicPageNum = 1;
                this.getTopicList(res.data.questionBankId, this.topicPageNum, this.topicPageSize);
                // 新增成功后启用导入和添加功能
                this.importEnabled = true;
                this.addEnabled = true;
              }
              this.$message.success(res.message);
              // 重置新增/编辑状态
              this.isEdit = false;
              this.isAdd = false;
            }
            this.submitLoading = false;
          });
        }
      });
    },

    /* 重置表单 */
    restForm(form) {
      this.$refs[form].resetFields();
    },

    /* 改变页数事件 */
    onChangePage(page, pageSize) {
      this.pageIndex = page;
      this.getBankList();
    },

    /* 改变每页显示条数 */
    onShowSizeChange(current, pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.getBankList();
    },

    /* 题库信息列表 */
    getBankList() {
      this.loading = true;
      this.searchForm.page = this.pageIndex;
      this.searchForm.rows = this.pageSize;
      req('post', '/bank/list', this.searchForm)
        .then((res) => {
          if (res.result === 'success') {
            this.dataList = res.data;
            this.QX = res.QX;
            if (!this.QX.edit && !this.QX.delete) {
              this.hideAction();
            } else if (columns[columns.length - 1].title !== '操作') {
              columns.push(actionShow);
            }
            this.totalPage = res.page.totalResult;
          }
          this.loading = false;
        }).catch((error) => {
        this.loading = false;
      });
    },

    /* 无所有行操作权限时,隐藏操作栏 */
    hideAction() {
      if (columns[columns.length - 1].title === '操作') {
        columns.splice(columns.length - 1, 1);
      }
    },

    /* 校验代号类型 */
    validCode(value) {
      if (value.length > 20) {
        value = value.slice(0, 20);
      }
      for (let i = value.length - 1; i >= 0; i--) {
        const unicode = value.charCodeAt(i);
        if (unicode > 65280 && unicode < 65375) {
          value = value.substr(0, i);
        }
      }
      this.value = value;
    },

    updateUserCourse(){
      req('post', '/quizRecord/reloadAndRefreshFakeQuiz', this.searchForm)
        .then((res) => {
          if (res.result === 'success') {
            this.$message.success(res.message);
          }
          this.loading = false;
        }).catch((error) => {
        this.loading = false;
      });
    },
  },
};
const actionShow = {
  title: '操作',
  width: '200px',
  hide: true,
  dataIndex: 'action',
  key: 'action',
  align: 'center',
  scopedSlots: { customRender: 'action' },
};

const columns = [
  {
    title: '序号',
    width: '50px',
    align: 'center',
    customRender: (text, row, index) => index + 1,
  },
  {
    title: '题库名称',
    align: 'center',
    dataIndex: 'title',
    key: 'title',
    width: '120px',
  },
  {
    title: '涉及岗位',
    align: 'center',
    dataIndex: 'positionName',
    key: 'positionName',
    width: '110px',
  },
  {
    title: '题目数量',
    dataIndex: 'topicCount',
    key: 'topicCount',
    align: 'center',
    width: '180px',
  },
  {
    title: '操作',
    width: '150px',
    hide: true,
    dataIndex: 'action',
    key: 'action',
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
];
</script>
<style scoped>
.topic-list-container {
  max-height: calc(100vh - 400px);
  overflow-y: auto;
}

.pagination-wrapper {
  position: sticky;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 10px;
  z-index: 1;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 15px;
}

.topic-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.topic-item {
  border: 1px solid #e8e8e8;
  padding: 15px;
  border-radius: 4px;
  position: relative;
}

.topic-content {
  font-size: 16px;
  margin-bottom: 10px;
}

.options label {
  display: block;
  margin: 5px 0;
  font-size: 14px;
}

.options input[type="radio"] {
  margin-right: 5px;
}

/* 按钮禁用状态样式优化 */
.ant-upload.ant-upload-disabled .ant-upload-list,
.ant-btn[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
.topic-delete {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>

<style scoped>
@import "../../../assets/css/maincss.css";
</style>
